
import compose from "./compose"

function applyMiddleware(...middlewares) {
    return function (createStore) {
        return function (reducers) {
            let store = createStore(reducers)
            let dispatch;
            const middlewareAPI = {
                getState: store.getState,
                dispatch: (action) => dispatch(action) // 引用最新的dispatch 否则thank中的dispatch无法使用promise中间件的功能  
            }
            let chain = middlewares.map(middleware => middleware(middlewareAPI))
            dispatch = compose(...chain)(store.dispatch)
            return {
                ...store,
                dispatch
            }
        }
    }
}

export default applyMiddleware